package com.kmt.plaza.sevice.impl;

import com.kmt.plaza.dao.ShoppingCartMapper;
import com.kmt.plaza.entity.ShoppingCart;
import com.kmt.plaza.entity.UserAddress;
import com.kmt.plaza.sevice.ShoppingCartService;
import com.kmt.plaza.vo.ResStatus;
import com.kmt.plaza.vo.ResultVO;
import com.kmt.plaza.vo.ShoppingCartVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    private Logger logger = LoggerFactory.getLogger(ShoppingCartServiceImpl.class);
    @Override
    public ResultVO addShoppingCart(ShoppingCart shoppingCart) {
        logger.info("开始添加购物车......");
        shoppingCart.setCartTime(sdf.format(new Date()));
        int insert = shoppingCartMapper.insert(shoppingCart);
        //回填主键
//        int i = shoppingCartMapper.insertUseGeneratedKeys(shoppingCart);
        if(insert>0){
            return new ResultVO(ResStatus.OK,"success",null);
        }else{
            return new ResultVO(ResStatus.NO,"fail",null);
        }
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public ResultVO listShoppingCartByUserId(int userId) {
        logger.info("通过userId查询购物车列表开始......");
        List<ShoppingCartVO> list = shoppingCartMapper.selectShopCartByUserId(userId);
        ResultVO resultVO = new ResultVO(ResStatus.OK, "success", list);
        return resultVO;
    }

    @Override
    public ResultVO listShoppingCartByCids(String cids) {
        logger.info("订单结算，通过cids查询购物车记录开始......");
        String[] arr = cids.split(",");
        List<Integer> cartIds = new ArrayList<>();
        for(int i=0;i<arr.length;i++){
            cartIds.add(Integer.parseInt(arr[i]));
        }
        List<ShoppingCartVO> list = shoppingCartMapper.selectShoppingCartBycids(cartIds);
        ResultVO resultVO = new ResultVO(ResStatus.OK, "success", list);
        return resultVO;
    }

    @Override
    public ResultVO deleteShoppingCart(int cartId) {
        logger.info("删除购物车开始......");
        Example example = new Example(ShoppingCart.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("cartId",cartId);
        int i = shoppingCartMapper.deleteByExample(example);
        if(i>0){
            return new ResultVO(ResStatus.OK,"删除商品成功！",i);
        }else{
            return new ResultVO(ResStatus.NO,"删除商品失败！",null);
        }
    }
}
